﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		SimplyCategoryValidationAttribute.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            SimplyCategoryValidationAttribute.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Dexter.Web.Mvc.ViewModel.Backoffice.Binders;

namespace Dexter.Web.Mvc.ViewModel.Backoffice.Validators
{
	public class SimplyCategoryValidationAttribute : ValidationAttribute
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="SimplyCategoryValidationAttribute"/> class.
		/// </summary>
		public SimplyCategoryValidationAttribute ()
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="SimplyCategoryValidationAttribute"/> class.
		/// </summary>
		/// <param name="errorMessage">The error message.</param>
		public SimplyCategoryValidationAttribute ( string errorMessage ) : base ( errorMessage )
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="SimplyCategoryValidationAttribute"/> class.
		/// </summary>
		/// <param name="errorMessageAccessor">The function that enables access to validation resources.</param>
		/// <exception cref="T:System:ArgumentNullException">
		/// 	<paramref name="errorMessageAccessor"/> is null.</exception>
		public SimplyCategoryValidationAttribute ( Func<string> errorMessageAccessor ) : base ( errorMessageAccessor )
		{
		}

		/// <summary>
		/// Determines whether the specified value of the object is valid.
		/// </summary>
		/// <param name="value">The value of the object to validate.</param>
		/// <returns>
		/// true if the specified value is valid; otherwise, false.
		/// </returns>
		public override bool IsValid ( object value )
		{
			if ( value == null )
				return false;

			ICollection<SimplyCategoryBinder> categories = value as ICollection<SimplyCategoryBinder>;

			if ( categories == null )
				return false;

			IEnumerable<SimplyCategoryBinder> selectedCat = categories.Where ( x => !x.Name.IsNullOrEmpty () );

			return selectedCat.Any ();
		}
	}
}
